<?php

namespace app\user\model;

use think\Model;
use Carbon\Carbon;
use Exception;
use app\common\traits\model\TraitModel;
use think\exception\HttpException;
use think\Db;
use app\user\model\Notifys;
use \think\Session;
use think\Hook;
/**
* 心愿单模型类
* @method createWish([['region' => 22, 'start_date' => '2016-12-13', 'end_date' => '2016-12-21', 'score' => 700, 'offer' => 97], ['region' => 19, 'start_date' => '2016-12-8', 'end_date' => '2016-12-10', 'score' => 652, 'offer' => 60]]);
* @method bool cancelMeetTheDemand(array|string $wish_id) 取消满足需求
* @method bool meetTheDemand(array|string $wish_id) 满足需求
* @method bool cancelWish() 取消心愿
*/
class Wishs extends Model
{
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
	protected $type = [
		'region'=>'array'
	];	
    const POST_WISH_PRICE = 10;

    use TraitModel;

    public function users()
    {
        return $this->hasMany('app\user\model\WishUsers', 'wish_id');
    }
	public function getCityAttr($value){
		if($value==-1){
			return '';
		}
		$status = ['1'=>'北京','2'=>'上海','3'=>'三亚','4'=>'成都','5'=>'西安'];
	   return $status[$value];
	}
    /**
     * 发送通知
     * @param  array  $motifys_info [description]
     * @return [type]               [description]
     */
    public function notifys($motifys_info = [])
    {
        return  Notifys::createNotifys($motifys_info);
    }
    /**
     * 设置房车时间为满足心愿状态
     * @param [type] $caravan_id [description]
     * @param [type] $start_date [description]
     * @param [type] $end_date   [description]
     */
    public function setUserCaravanCarlendarIsWish($caravan_id, $start_date, $end_date = null)
    {
        return model('Calendar')->setUserCaravanCarlendarIsWish($caravan_id, $start_date, $end_date);
    }
    /**
     * 取消设置房车时间为心愿状态
     * @param [type] $caravan_id  [description]
     * @param [type] $cancel_date [description]
     */
    public function setUserCaravanCarlendarIsUnWish($caravan_id, $cancel_date)
    {
        return model('Calendar')->setUserCaravanCarlendarIsUnWish($caravan_id, $cancel_date);
    }
    /**
     * 校验房车是否可以满足心愿
     * @param  [type] $caravan_id [description]
     * @param  [type] $start_date [description]
     * @param  [type] $end_date   [description]
     * @return [type]             [description]
     */
    public function checkUserCaravanDateSetWish($caravan_id, $start_date, $end_date = null)
    {
        return model('Calendar')->checkUserCaravanDateSetWish($caravan_id, $start_date, $end_date);
    }
    /**
     * 获取用户积分
     * @return [type] [description]
     */
    public function getUserIntegral()
    {
        return model('Intergrates')->getUserIntegral();
    }
    /**
     * 消费积分
     * @param  [type] $intergrates [description]
     * @return [type]              [description]
     */
    public function reduceIntergrates($intergrates, $remark = '悬赏消费')
    {
        return model('Intergrates')->reduceIntergrates($intergrates, null, ['remark' => $remark], true);
    }
    /**
     * 增加积分
     * @param [type] $intergrates [description]
     * @param [type] $user_id     [description]
     */
    public function addIntergrates($intergrates, $user_id = null, $remark = '取消悬赏退还')
    {
        return model('Intergrates')->addIntergrates($intergrates, $user_id, ['remark' => $remark]);
    }
    /**
     * 获取用户房车信息
     * @param  [type] $user_id [description]
     * @param  string $field   [description]
     * @return [type]          [description]
     */
    public function getCaravanInfo($user_id, $field = '')
    {
        return model('user/CaravanInfos')->getCaravanInfo($user_id, $field);
    }
    /**
     * 创建心愿
     * @param  [type] $wish_info [description]
     * @return [type]            [description]
     */
    public function createWish($wish_info)
    {
        if (empty($wish_info)) {
            return false;
        }
        if (is_array($wish_info) && key($wish_info) !== 0) {
            $wish_info = [$wish_info];
        }
        $intergrates = $postwishprices = 0;
        foreach ($wish_info as $_wish_info) {
			if(!empty($_wish_info['score'])){
				if (!is_numeric($_wish_info['score']) || $_wish_info['score'] < 0) {
	                // throw new HttpException(-1, "Integral can not be negative");
	                $this->error = ['code' => -200, 'msg' => lang('Integral can not be negative or Integration format error')];
	                return false;
	            }
			}
            $intergrates    += abs($_wish_info['score']);
            $postwishprices += self::POST_WISH_PRICE;
        }
        if ($this->getUserIntegral() < $postwishprices) {
        	$this->error = ['code' => -300, 'msg' => lang('notEnough')];
            Session::set('redirect_url', '/wishs/create');
        	//return 'notEnough';
            return false;
        }
        // if ($this->getUserIntegral() < $intergrates + $postwishprices) {
        //     $this->error = ['code' => -300, 'msg' => lang('notEnough')];
        //     //return 'notEnough';
        //     return false;
        // }
        $this->startTrans();
        try {
            //$this->reduceIntergrates($intergrates);
            $this->reduceIntergrates($postwishprices, '发布心愿单');
            foreach ($wish_info as $_wish_info) {
                self::create(array_merge($_wish_info, ['user_id' => self::getLoginUserInfo('id')]), true);
            }
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
			$this->error = ['code' => -200, 'msg' => lang('unknown error')];
            return false;
        }
        queue('app\common\job\JobPay@WishNotice',$wish_info, $delay = 0, $queue = 'order');
        return true;        
    }
    /**
     * 获取用户心愿列表
     * @return [type] [description]
     */
    public function getWishList($querys = [])
    {
    	return self::getInfoList(array_merge($querys , ['user_id' => self::getLoginUserInfo('id')]));
    }
    /**
     * 获取心愿详情
     * @param  [type] $wish_id [description]
     * @param  string $field   [description]
     * @return [type]          [description]
     */
    public function getWish($where = [], $field = '')
    {
        if (empty($where)) {
            return ;
        }
        $wish = self::get($where);
        if ($field) {
            if (isset($wish->$field)) {
                return $wish->$field; 
            }
            return ;
        }
        return $wish;
    }
    /**
     * [getWishs description]
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    private function getWishs($where = [])
    {
        return self::all($where);
    }
    /**
     * 获取心愿状态
     * @param  [type] $wish_id [description]
     * @return [type]          [description]
     */
    public function getWishStatus($where = [])
    {
        return $this->getWish($where, 'status');
    }
    /**
     * 修改心愿
     * @param  array  $where     [description]
     * @param  array  $wish_info [description]
     * @return [type]            [description]
     */
    public function updateWish($wish_id, $wish_info = [])
    {
        $wish = $this->getWish(['id' => $wish_id, 'user_id' => self::getLoginUserInfo('id')]);
        if ($wish->status === 0 && $wish->users()->count() == 0) {
        	if(!empty($_wish_info['score'])){
	            if (!is_numeric($wish_info['score']) || $wish_info['score'] < 0) {
	            	 $this->error = ['code' => -200, 'msg' => lang('Integral can not be negative or Integration format error')];
	                return false;
	            } 
			}
            // if ($wish_info['score'] > $wish->score) {
            //     if ($this->getUserIntegral() < ($wish_info['score'] - $wish->score)) {
            //         $this->error = ['code' => -300, 'msg' => lang('notEnough')];
            //         return false;
            //     }
            // }
            $intergrates = abs($wish_info['score'] - $wish->score);

            $this->startTrans();
            try {
                // if ((int)$intergrates != 0) {
                //     if ($wish_info['score'] > $wish->score) {
                //         $this->reduceIntergrates($intergrates, '修改心愿补足差额');
                //     }else{
                //         $this->addIntergrates($intergrates, null, '修改心愿退还差额');
                //     }
                // }
                $this->update($wish_info, ['id' => $wish_id, 'user_id' => self::getLoginUserInfo('id')],true);
                $this->commit();   
            } catch (Exception $e) {
                $this->rollback();
				$this->error = ['code' => -200, 'msg' => lang('unknown error')];
                return false;
            }
            return true;
        }
		$this->error = ['code' => -200, 'msg' => lang('unknown error')];
        return false;
    }
    /**
     * 取消心愿
     * @param  [type] $wish_id [description]
     * @return [type]          [description]
     */
    public function cancelWish($wish_id,$mark='')
    {
    	if($mark===true){
    		 $where = array_merge(['id' => ['in', $wish_id], 'status' => 0]);
    	}else{
    		$where = array_merge(['id' => ['in', $wish_id], 'user_id' => self::getLoginUserInfo('id'), 'status' => 0]);
    	}
        $wishs = $this->getWishs($where);
        if (!$wishs) {
            return false;
        }

        $this->startTrans();
        try {
            foreach ($wishs as $wish) {
                $meet_user_ids = $wish->users()->column('meet_user_id');
                //$this->addIntergrates($wish->score, null, '取消心愿退还');
                foreach ($meet_user_ids as $meet_user_id) {
                    $this->syncCancelMeetTheDemand($wish->id, $meet_user_id);
                }
                $wish->users()->delete();
                $wish->delete(); 
            }
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return true;
    }
    /**
     * 完成心愿
     * @param  [type] $wish_id      [description]
     * @param  [type] $meet_user_id [description]
     * @return [type]               [description]
     */
    protected function meetWish($wish_id, $meet_user_id)
    {
        $wish = $this->getWish(['id' => $wish_id, 'status' => 0]);
        $wish->status = 1;
        $wish->save();
        $u = $wish->users()->where('meet_user_id', $meet_user_id)->update(['status' => 1]);

        $this->syncCancelWish($wish_id, self::createDateRange($wish->start_date, $wish->end_date));
    }
    /**
     * 设置房车状态
     * @param [type]  $caravan_id [description]
     * @param [type]  $start_date [description]
     * @param [type]  $end_date   [description]
     * @param integer $status     [description]
     * @param array   $querys     [description]
     * @param boolean $syn        [description]
     */
    private function setCaravanCarlendarIsOrders($caravan_id, $start_date, $end_date, $querys = ['orders' => ['not in', '0']], $syn = false)
    {
        return model('user/Calendar')->setUserCaravanCarlendarIsOrders($caravan_id, $start_date, $end_date, '', $querys, $syn);
    }
    /**
     * 根据心愿创建订单
     * @param  [type] $wish_id      [description]
     * @param  [type] $meet_user_id [description]
     * @return [type]               [description]
     */
    public function createOrder($wish_id, $meet_user_id, $order_info)
    {
        $wish = $this->getWish(['id' => $wish_id, 'status' => 0, 'user_id' => self::getLoginUserInfo('id')]);
        if (!$wish) {
            return false;
        }
        $this->startTrans();
        try {
            $this->meetWish($wish_id, $meet_user_id);
            $meet_user  = $wish->users()->where(['meet_user_id' => $meet_user_id])->find();
			//接单未成功用户的id
            $meet_id = $wish->users()->where(['meet_user_id'=>['NEQ',$meet_user_id],'wish_id'=>$wish_id])->value('meet_user_id');
            model('Orders')->createWishOrder($order_info);//创建订单
            //$this->addIntergrates($wish->score, $meet_user_id, '心愿悬赏');//增加积分
            //
            $this->commit(); 
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
		if(!empty($meet_id)){
			$this->notifys(['users_id' => $meet_id, 'body' => '@wishuser']);
		}
        return true;
    }
    public function toMe($wish_id = null)
    {
        $this->getWishs();
    }
    /**
     * 满足需求
     * @param [type] $wish_id [description]
     */
    public function meetTheDemand($wish_id)
    {
    	//查看当前会员是否已接该单
    	$wish_users = model('WishUsers')->where(['wish_id'=>$wish_id,'meet_user_id'=>self::getLoginUserInfo('id')])->find();
		if($wish_users){
			return true;
		}
        $wishs = $this->getWishs(['id' => ['in', $wish_id], 'user_id' => ['NEQ', self::getLoginUserInfo('id')]]);
        if (!$wishs) {
            return false;
        }
        $caravan_id = $this->getCaravanInfo(['user_id' => self::getLoginUserInfo('id')], 'id');
        if (!$caravan_id) {
        	$this->error = '系统没有您的房车';
            return false;
        }
        //data数据
        $data['caravan_id'] = $caravan_id;
        $data['email']    = model('Users')->where('id',$this->where('id',$wish_id)->value('user_id'))->value('email');
        $this->startTrans();
        try {
            foreach ($wishs as $wish) {
                if (true == $this->checkUserCaravanDateSetWish($caravan_id, $wish->start_date, $wish->end_date)) {
                        //更新日历 锁定时间
                    $wish->users()->save(['meet_user_id' => self::getLoginUserInfo('id'), 'caravan_id' => $caravan_id]);
                    $this->setUserCaravanCarlendarIsWish($caravan_id, $wish->start_date, $wish->end_date);
                    $this->notifys(['users_id' => $wish->user_id, 'body' => '@wish']);
                }else{
                	$this->error = '您的房车无法满足该心愿';
                    return false;
                }    
                // if (!$wish->users) {
                //     if (true == $this->checkUserCaravanDateSetWish($caravan_id, $wish->start_date, $wish->end_date)) {
                //         //更新日历 锁定时间
                //         $wish->users()->save(['meet_user_id' => self::getLoginUserInfo('id'), 'caravan_id' => $caravan_id]);
                //         $this->setUserCaravanCarlendarIsWish($caravan_id, $wish->start_date, $wish->end_date);
                //         $this->notifys(['users_id' => $wish->user_id, 'body' => '@wish']);
                //     }   
                // }
            }
            Hook::exec('app\\behavior\\Test','run',$data);//行为
            $this->commit();         
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return true;  
    }
    /**
     * 取消满足需求
     * @param  [type] $wish_id [description]
     * @return [type]          [description]
     */
    public function cancelMeetTheDemand($wish_id, $user_id = null)
    {
        if (is_scalar($wish_id)) {
            $wish_id = explode(',', $wish_id);
        }

        $user_id = $user_id  ? : self::getLoginUserInfo('id');

        $this->startTrans();
        try {
            $wishs = self::hasWhere('users', ['meet_user_id' => $user_id])->select();
            $this->syncCancelMeetTheDemand($wish_id, $user_id);
            foreach ($wishs as $wish) {
                if (in_array($wish->id, $wish_id)) {
                    $wish->users()->where(['meet_user_id' => $user_id])->delete();
                }
            }
            $this->commit();          
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return true;
    }
    /**
     * 同步取消需求
     * @param  [type] $wish_id [description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    protected function syncCancelMeetTheDemand($wish_id, $user_id = null)
    {
        if (is_scalar($wish_id)) {
            $wish_id = explode(',', $wish_id);
        }
        if ($caravan_id = $this->getCaravanInfo(['user_id'=>$user_id], 'id')) {
            $old_date = $all = [];
            $wishs = self::hasWhere('users', ['meet_user_id' => $user_id])->select();
            foreach ($wishs as $wish) {
                $all = array_merge($all, self::createDateRange($wish->start_date, $wish->end_date));
                if (!in_array($wish->id, $wish_id)) {
                    $old_date = array_merge($old_date, self::createDateRange($wish->start_date, $wish->end_date));
                }
            }

            if ($cancel_date = array_unique(array_diff($all, $old_date))) {
                    //更新日历 解锁锁定时间 setUserCaravanCarlendarIsUnLock
                $this->setUserCaravanCarlendarIsUnWish($caravan_id, $cancel_date);
            }
        }        
    }
    /**
     * 同步取消心愿
     * @param  [type] $wish_id [description]
     * @param  array  $dates   [description]
     * @return [type]          [description]
     */
    protected function syncCancelWish($wish_id, $dates = [])
    {
        $wishs = self::hasWhere('users', ['wish_id' => ['NEQ', $wish_id]])->where('user_id', self::getLoginUserInfo('id'))->select();
        foreach ($wishs as $wish) {
            $meet_user_ids = $wish->users()->where(['wish_id' => ['NEQ', $wish_id]])->column('meet_user_id');
            foreach ($meet_user_ids as $meet_user_id) {
                $this->syncCancelMeetTheDemand($wish->id, $meet_user_id);
            }
        }
    }
	
	/**
	 * 获取全部心愿列表
	 */
	public function getWishsList($start_date,$end_date,$page){
		if(!$start_date && !$end_date){
			$param['user_id'] = ['NEQ',self::getLoginUserInfo('id')];
			$param['status'] = ['NEQ',1];
			$param['start_date'] = ['>',date('Y-m-d',time())];
			$param['city'] = model('Camps')->where('id',model('Users')->where('id',self::getLoginUserInfo('id'))->value('camp_id'))->value('area');
			return $this->where($param)->page($page,6)->order('created_at desc')->select();
		}
		$param['end_date'] = ['EGT',$start_date];
		$param['user_id'] = ['NEQ',self::getLoginUserInfo('id')];
		$param['status'] = ['NEQ',6];
		$param['start_date'] = [['>',date('Y-m-d',time())],['ELT',$end_date]];
		$param['city'] = model('Camps')->where('id',model('Users')->where('id',self::getLoginUserInfo('id'))->value('camp_id'))->value('area');
		return $this
				->where($param)
				->page($page,6)
				->order('created_at desc')
				->select();
	}
	
	/**
	 * 获取地址
	 */
	public function getAddress($array_address){
	    $address = Db::table('area')->where('AREA_CODE',$array_address)->value('AREA_NAME');
	    return $address;
	}
}
